package com.coinworld.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @description
 * @author:
 * @create: 2019-08-23 18:05
 **/
@Slf4j
public class CSVUtil {

    /**
     * 写入csv结束，写出流
     */
    public static void outCsvStream(HttpServletRequest request,HttpServletResponse response, File tempFile,String fileName) throws IOException {
        OutputStream out = response.getOutputStream();
        File fileLoad = new File(tempFile.getCanonicalPath());
        FileInputStream in = new FileInputStream(fileLoad);
        try {
            byte[] b = new byte[10240];
            response.reset();
            response.setContentType("application/csv");
            if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                response.setHeader("Content-Disposition","attachment; "
                        + "filename=" + new String(fileName.getBytes("GBK"),"ISO8859-1") + ".csv");
            }else{
                //firefox、chrome、safari、opera
                response.setHeader("Content-Disposition","attachment; "
                        + "filename="+ new String(fileName.getBytes("UTF8"), "ISO8859-1") + ".csv");
            }
            int n;
            //为了保证excel打开csv不出现中文乱码
            out.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
            while ((n = in.read(b)) != -1) {
                //每次写入out1024字节
                out.write(b, 0, n);
            }
        }catch (Exception e){
            log.error("============> 写入csv结束，写出流 error");
        }finally {
            in.close();
            out.close();
        }
    }

    /**
     * 删除单个文件
     *
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(File file) {
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

}
